package com.sanmubird.mywebframework.indicator.domain.executor;

import com.alibaba.fastjson.JSONObject;
import com.sanmubird.mywebframework.indicator.domain.model.Indicator;
import com.sanmubird.mywebframework.indicator.domain.model.IndicatorExecutor;
import com.sanmubird.mywebframework.indicator.domain.model.IndicatorValueType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Map;


/**
 * @author sam
 */
@Slf4j
public class SqlExecutor implements IndicatorExecutor {

    private final SqlParser parser = new SqlParser();
    private final Map<String, JdbcTemplate> jdbcTemplateMap;

    /**
     * sql语句
     */
    private static final String SQL = "sql";
    /**
     * 数据源
     */
    private static final String DATA_SOURCE = "dataSource";


    public SqlExecutor(Map<String, JdbcTemplate> jdbcTemplateMap) {
        this.jdbcTemplateMap = jdbcTemplateMap;
    }

    @Override
    public Object execute(Indicator indicator, JSONObject queryParams) {
        JSONObject params = indicator.getParams();
        String sql = params.getString(SQL);
        String dataSource = params.getString(DATA_SOURCE);
        String formatSql = parser.parse(sql, queryParams);
        if (indicator.getValueType().equals(IndicatorValueType.SINGLE)) {
            JdbcTemplate jdbcTemplate = jdbcTemplateMap.get(dataSource);
            return jdbcTemplate.queryForMap(formatSql);
        } else if (indicator.getValueType().equals(IndicatorValueType.MULTIPLE)) {
            JdbcTemplate jdbcTemplate = jdbcTemplateMap.get(dataSource);
            return jdbcTemplate.queryForList(formatSql);
        } else {
            log.error("返回值类型配置错误");
            return null;
        }
    }
}
